package cn.itcast.controller;

import cn.itast.domain.Role;
import cn.itast.domain.UserInfo;
import cn.itcast.service.IUserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/users")
public class UserController {
    @Autowired
    private IUserService userService;

    @RequestMapping("/findAll")
    public ModelAndView findAll(@RequestParam(name = "page", required = true, defaultValue = "1") Integer page,
                                @RequestParam(name = "size", required = true, defaultValue = "4") Integer size) {
        ModelAndView mv = new ModelAndView();
        List<UserInfo> users = userService.findAll(page, size);
        PageInfo pageInfo = new PageInfo(users);

        mv.addObject("pageInfo",pageInfo);
        mv.setViewName("user-list");
        return mv;
    }

    @RequestMapping("/findById.do")
    @Secured("ROLE_ADMIN")
    public ModelAndView findById(@RequestParam(name = "id",required = true)String userId){

        ModelAndView mv = new ModelAndView();
        UserInfo user =userService.findById(userId);

        mv.addObject("user",user);
        mv.setViewName("user-show");

        return mv;
    }

    @RequestMapping("/save")
    public String save(UserInfo userInfo){
        userService.save(userInfo);
        return "redirect:findAll.do";
    }

    @RequestMapping("/findAndUpdateByUserId")
    public ModelAndView findAndUpdateByUserId(@RequestParam(name = "id",required = true)String userId){
        ModelAndView mv =new ModelAndView();
        UserInfo userInfo = userService.findById(userId);
        List<Role> roleList=userService.findOtherRole(userId);

        mv.addObject("user",userInfo);
        mv.addObject("roleList",roleList);
        mv.setViewName("user-role-add");
        return mv;

    }

    @RequestMapping("/addRoleToUser")
    public String addRoleToUser(@RequestParam(name = "userId", required = true)String userId,
                                @RequestParam(name = "roleId", required = true)String[] roleId){
        userService.addRoleToUser(userId,roleId);

        return "redirect:findAll.do";
    }

}
